package com.lfd.springboottransaction;

import com.lfd.springboottransaction.controller.CourseController;
import com.lfd.springboottransaction.pojo.Course;
import com.lfd.springboottransaction.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.Mapping;

@EnableTransactionManagement
@SpringBootApplication
@MapperScan(value = "com.lfd.springboottransaction.mapper")
@Slf4j
public class SpringbootTransactionApplication implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
//        test();
        courseController.testTransactional();
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTransactionApplication.class, args);
    }
    @Autowired
    private CourseController courseController;
//    确保 test() 方法是由 Spring 管理的 bean 调用的。如果你在同一个类中直接调用
//    test() 方法，它不会触发事务，因为 Spring 事务仅在代理对象之间调用时才生效。请确保从另一个
//    bean 或组件中调用 test() 方法。
    @Autowired
    private CourseService courseService;

    @Transactional
    protected void test() {
        boolean save1 = courseService.save(Course.builder().name("张三44").build());
        log.info("save1======{}", save1);
        int i = 1 / 0;
        boolean save2 = courseService.save(Course.builder().name("张三55").build());
        log.info("save2======{}", save2);
    }

}
